// 加载微信小程序
import api from "@/api";
import type {getSessionIdResType} from "@/types/third";
import {useThirdStore} from "@/stores";
const thirdStore = useThirdStore()

function load(){
    getSessionId();
}

const getSessionId = async (auto_login = null) => {
    // 获取code
    let codeStr = '';
    const loginResult = await uni.login();
    console.log('loginResult', loginResult)
    if (loginResult.errMsg === 'login:ok') {
        codeStr = loginResult.code;
    } else {
        return false;
    }
    await api.third.getSessionIdApi({
        platform: 'miniApp',
        payload: encodeURIComponent(JSON.stringify({
            code: codeStr,
            auto_login
        }))
    }).then((res: ApiResponse<getSessionIdResType>) => {
        if (res.code == 1) {
            thirdStore.setSessionId(res.data.session_id)
            return true;
        }
        return false;
    })
}
// 微信登录
const login = async () => {
    await api.third.wechatLoginApi({
        platform: 'miniApp',
        payload: encodeURIComponent(JSON.stringify({
            sessionId: thirdStore.sessionId,
        }))
    }).then((res: ApiResponse) => {
        return true
    })
    return false
}

// 绑定用户手机号
const bindUserPhoneNumber = async (e:any)=>{
    const {code}=await api.third.bindUserPhoneNumberApi({
        platform: 'miniApp',
        payload: encodeURIComponent(JSON.stringify({
            sessionId: thirdStore.sessionId,
            iv:e.iv,
            encryptedData:e.encryptedData,
            code:e.code
        }))
    })
    if(code===1){
        return true
    }
    return false
}


export default {
    load,
    login,
    bindUserPhoneNumber
}